<?php
namespace Event\Drive\Data\Cache;
use Event\Drive\Exceptions\EventDriveCacheException;
use \Redis as Redis;

class CacheConnect
{

    /**
     * @var Redis | null;
     */
    static private $instance;

    /**
     * @var Redis
     */
    static private $redis;

    //防止直接创建对象
    private function __construct(array $options){
        if (!extension_loaded('redis')) {
            throw new \BadFunctionCallException('not support: redis');
        }
        $redis = new \Redis;

        try {
            $timeout = $options['timeout'] ?? 0;
            if (!empty($options['persistent'])) {
                $persistentId = 'persistent_id_' . $options['select'];
                $redis->pconnect($options['host'], $options['port'], $timeout, $persistentId);
            } else {
                $redis->connect($options['host'], $options['port'], $timeout);
            }

            if (!empty($options['password'])) {
                $redis->auth($options['password']);
            }

            if (!empty($options['select'])) {
                $redis->select($options['select']);
            }

            // 检查连接是否成功
            if (!$redis->ping()) {
                throw new \Exception('Failed to establish a Redis connection');
            }

            self::$redis = $redis;
        } catch (\Exception $e) {
            // 日志记录或其它处理
            throw new \Exception('Error initializing Redis connection: ' . $e->getMessage());
        }
    }
    //防止克隆对象
    private function __clone(){

    }
    static public function getRedis(){
        //目前只支持ThinkPHP5与Laravel 的配置
        $config = config('eventdrive.database.redis');
        if (!$config) {
            throw new EventDriveCacheException('redis config is not found');
        }
        //没有则创建
        if (!isset(self::$instance) || !(self::$instance instanceof self)) {
            self::$instance = new self($config);
        }
        //注意这里的返回是redis而不是object本身,这是因为我们只需要绑定在本单例下的redis对象
        return self::$redis;
    }
}
